import Vue from 'vue'
import Vuex from 'vuex'
import App from './App'
import Music from './models/music.js'

Vue.use(Vuex)
Vue.config.productionTip = false

App.mpType = 'app'

function judgeCurLyricIndex(arr,start,end,playTime){//判断当前应该高亮的歌词的数组索引
	if(end >= arr.length ) end = arr.length - 1;
	if(start == end){
			return start;
	}
	else{
		 var mid = start + Math.floor((end - start)/2);
		 var activeTime = arr[mid].activeTime * 1000;
		 if(playTime == activeTime){
				 return mid;
		 }
		 else if(playTime < activeTime){
				 if(mid == 0){
						 return mid;
				 }
				 else if(playTime >= arr[mid-1].activeTime * 1000){
						 return mid - 1;
				 }
				 else{
						 return judgeCurLyricIndex(arr,start,mid-2,playTime);
				 }
		 }
		 else{
				 if(mid == arr.length - 1){
						 return mid;
				 }
				 else if(playTime < arr[mid+1].activeTime * 1000){
						 return mid;
				 }
				 else{
						 return judgeCurLyricIndex(arr,mid+1,end,playTime);
				 }
		 }
	}
}

const store = new Vuex.Store({
  state: {
		volume: 0.5,// 全局音量，0~1
		playing: false,// 是否在播放歌曲
    music: new Music()// 初始化一个空的音乐类
	},
	getters: {
		playTime(state) {// 单位歌曲播放到的时间，单位秒
			if(state.music.progress == 100) return state.music.length;
			return state.music.progress * state.music.length / 100;
		},
		lyricIndex(state) {
			return judgeCurLyricIndex(state.music.lyrics, 0, state.music.lyrics.length-1, store.getters.playTime * 1000);
		}
	},
  mutations: {
		// 统一设值方法，obj参数应为对象
		setState (state, obj) {
			Object.assign(state, obj);
		},
    setVolume (state, volume) {
      state.volume = volume;
    },
		setPlaying (state, playing) {
			state.playing = playing;
		},
		setMusic (state, music) {
			state.music = music;
		},
		setPlayProgress(state, progress) {
			state.music.progress = progress;
		}
  }
})
Vue.prototype.$store = store// 在非web端，$store不能自动注入每个子组件，所以手动在应用程序原型中注入$store
const app = new Vue({
    ...App,
		store
})
app.$mount()
